

using System;
using System.Linq;
using System.Web;
using Payroll.BusinessLogic.Caching;
using Payroll.BusinessLogic.Data;
using Payroll.Common;
using Payroll.Common.Utils;

namespace Payroll.BusinessLogic.Audit
{
    /// <summary>
    /// Log service
    /// </summary>
    public partial class LogService : ILogService
    {
        #region Fields

        /// <summary>
        /// Object context
        /// </summary>
        private readonly PayrollHRDataContext m_context;

        /// <summary>
        /// Cache manager
        /// </summary>
        private readonly ICacheManager _cacheManager;

        #endregion

        #region Ctor

        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="context">Object context</param>
        public LogService(PayrollHRDataContext context)
        {
            this.m_context = context;
            this._cacheManager = new PayrollRequestCache();
        }

        #endregion


        public void DeleteLog(int logId)
        {
            throw new NotImplementedException();
        }

        public void ClearLog()
        {
            var log = m_context.Logs.ToList();
            foreach (var logItem in log)
                m_context.Logs.DeleteOnSubmit(logItem);
            m_context.SubmitChanges();
        }

        public PagedList<Log> GetAllLogs(DateTime? createdOnFrom, DateTime? createdOnTo, string message, int logTypeId, int pageIndex, int pageSize)
        {
            var query = from l in m_context.Logs
                        where (!createdOnFrom.HasValue || createdOnFrom.Value.Month <= l.CreatedOn.Month) &&
                        (!createdOnTo.HasValue || createdOnTo.Value.Month >= l.CreatedOn.Month) 
                        //&& (logTypeId == 4 || logTypeId == l.LogTypeID) 
                        && (String.IsNullOrEmpty(message) || l.Message.Contains(message) || l.Exception.Contains(message))
                        orderby l.CreatedOn descending
                        select new Log
                        {
                            EmployeeId = l.EmployeeID,
                            IPAddress = l.IPAddress,
                            LogId = l.LogID,
                            Message = l.Message,
                            PageUrl = l.PageURL
                        };
            var log = new PagedList<Log>(query, pageIndex, pageSize);
            return log;
        }

        public Log GetLogById(int logId)
        {
            throw new NotImplementedException();
        }

        public Log InsertLog(LogTypeEnum logType, string message, string exception)
        {
            return InsertLog(logType, message, new Exception(String.IsNullOrEmpty(exception) ? string.Empty : exception));
        }

        public Log InsertLog(LogTypeEnum logType, string message, Exception exception)
        {
            int customerId = 0;
            if (PayrollContext.Current.User != null)
                customerId = PayrollContext.Current.User.EmployeeId;
            string IPAddress = PayrollContext.Current.UserHostAddress;
            string pageUrl = CommonHelper.GetThisPageUrl(true);

            return InsertLog(logType, 11, message, exception, IPAddress, customerId, pageUrl);
        }

        
        public Log InsertLog(LogTypeEnum logType, int severity, string message,
        Exception exception, string IPAddress,
        int employeeId, string pageUrl)
        {
            //don't log thread abort exception
            if ((exception != null) && (exception is System.Threading.ThreadAbortException))
                return null;

            string exceptionStr = exception == null ? string.Empty : exception.ToString();

            string referrerUrl = string.Empty;
            if (HttpContext.Current != null &&
                HttpContext.Current.Request != null &&
                HttpContext.Current.Request.UrlReferrer != null)
                referrerUrl = HttpContext.Current.Request.UrlReferrer.ToString();

            message = CommonHelper.EnsureNotNull(message);
            message = CommonHelper.EnsureMaximumLength(message, 1000);
            exceptionStr = CommonHelper.EnsureNotNull(exceptionStr);
            exceptionStr = CommonHelper.EnsureMaximumLength(exceptionStr, 4000);
            IPAddress = CommonHelper.EnsureNotNull(IPAddress);
            IPAddress = CommonHelper.EnsureMaximumLength(IPAddress, 100);
            pageUrl = CommonHelper.EnsureNotNull(pageUrl);
            pageUrl = CommonHelper.EnsureMaximumLength(pageUrl, 100);
            referrerUrl = CommonHelper.EnsureNotNull(referrerUrl);
            referrerUrl = CommonHelper.EnsureMaximumLength(referrerUrl, 100);


            var log = new BusinessLogic.Data.Log { LogTypeID = (int)logType, Severity = severity, Message = message, Exception = exceptionStr, IPAddress = IPAddress, EmployeeID = employeeId, PageURL = pageUrl, ReferrerURL = referrerUrl, CreatedOn = DateTime.UtcNow };
            m_context.Logs.InsertOnSubmit(log);
            m_context.SubmitChanges();

            return new Log { LogId = log.LogID, LogTypeId = log.LogTypeID };
        }


        public PagedList<Log> GetAllLogs(int year, int month, int pageIndex, int pageSize)
        {
            var query = from l in m_context.Logs
                        where l.CreatedOn.Year == year && l.CreatedOn.Month == month
                        orderby l.CreatedOn descending
                        select new Log
                        {
                            EmployeeId = l.EmployeeID,
                            IPAddress = l.IPAddress,
                            LogId = l.LogID,
                            Message = l.Message,
                            PageUrl = l.PageURL
                        };
            var log = new PagedList<Log>(query, pageIndex, pageSize);
            return log;
        }
    }
}
